/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package tx

import (
	"github.com/spf13/cobra"
	"hundsun.com/hsl/hschain/cmd/cli/common"
	"hundsun.com/hsl/hschain/common/util"
	"hundsun.com/hsl/hschain/protos/ledger"
	protosrpc "hundsun.com/hsl/hschain/protos/rpc"
	service "hundsun.com/hsl/hschain/rpc/impl"
)

func queryTxByHashCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "query",
		Short: "Query tx by hash",
		Long:  "Query tx by hash",
		Run:   queryTxByHash,
	}

	cmd.Flags().StringP("hash", "", "", "transaction hash")
	cmd.MarkFlagRequired("hash")

	return cmd
}

func queryTxByHash(cmd *cobra.Command, args []string) {
	hash, _ := cmd.Flags().GetString("hash")
	rpcLaddr, _ := cmd.Flags().GetString(common.FlagRPCLaddr)
	param := &protosrpc.TxHashParam{
		TxHash: hash,
	}

	common.RPCCall(rpcLaddr, service.GetTransactionByHash, param,
		func(res interface{}) {
			obj := res.(service.JSONRPCResp)
			valI, _ := util.Bytes2Struct(&ledger.ExecutedTransaction{}, obj.Payload)
			val := valI.(*ledger.ExecutedTransaction)
			common.PrintJSON(common.FromPbExecTransaction(val))
		})
}
